/**
 * 优化面板主组件
 * 整合质量报告、SEO分析、可读性分析、版本对比
 */

import React, { useState } from 'react';
import { Card, Button, Tabs, Space, message, Modal, Spin } from 'antd';
import {
  ThunderboltOutlined,
  FileTextOutlined,
  SearchOutlined,
  ReadOutlined,
  CompareOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import { useOptimizerStore } from '@/stores/optimizer.store';
import { useEditorStore } from '@/stores/editor.store';
import { QualityReport } from './QualityReport';
import { SEOPanel } from './SEOPanel';
import { ReadabilityPanel } from './ReadabilityPanel';
import { VersionCompare } from './VersionCompare';
import './style.css';

const { TabPane } = Tabs;

export const OptimizationPanel: React.FC = () => {
  const { content } = useEditorStore();

  const {
    isAnalyzing,
    isOptimizing,
    qualityReport,
    seoAnalysis,
    readabilityAnalysis,
    optimizedVersions,
    selectedVersionId,
    comparisonData,
    analyzeAll,
    optimizeArticle,
    applySuggestion,
    generateOptimizedVersions,
    selectVersion,
    compareVersions,
    exportReport,
  } = useOptimizerStore();

  const [activeTab, setActiveTab] = useState('quality');
  const [showVersionModal, setShowVersionModal] = useState(false);

  /**
   * 开始分析
   */
  const handleAnalyze = async () => {
    if (!content || content.trim().length === 0) {
      message.warning('请先输入文章内容');
      return;
    }

    message.loading({ content: '正在分析...', key: 'analyze', duration: 0 });

    try {
      await analyzeAll(content);
      message.success({ content: '分析完成！', key: 'analyze' });
    } catch (error) {
      message.error({ content: '分析失败，请重试', key: 'analyze' });
    }
  };

  /**
   * 一键优化
   */
  const handleQuickOptimize = async (type: 'seo' | 'readability' | 'professional') => {
    if (!content) {
      message.warning('请先输入文章内容');
      return;
    }

    message.loading({ content: '正在优化...', key: 'optimize', duration: 0 });

    try {
      await optimizeArticle(type);
      message.success({ content: '优化完成！', key: 'optimize' });

      // 显示优化后的版本
      setShowVersionModal(true);
    } catch (error) {
      message.error({ content: '优化失败，请重试', key: 'optimize' });
    }
  };

  /**
   * 生成多个版本
   */
  const handleGenerateVersions = async () => {
    if (!content) {
      message.warning('请先输入文章内容');
      return;
    }

    message.loading({ content: '正在生成多个优化版本...', key: 'versions', duration: 0 });

    try {
      await generateOptimizedVersions();
      message.success({ content: '版本生成完成！', key: 'versions' });
      setShowVersionModal(true);
    } catch (error) {
      message.error({ content: '版本生成失败，请重试', key: 'versions' });
    }
  };

  /**
   * 应用建议
   */
  const handleApplySuggestion = async (suggestionId: string) => {
    message.loading({ content: '正在应用建议...', key: 'apply' });

    try {
      await applySuggestion(suggestionId);
      message.success({ content: '建议已应用', key: 'apply' });
    } catch (error) {
      message.error({ content: '应用失败', key: 'apply' });
    }
  };

  /**
   * 导出报告
   */
  const handleExportReport = async () => {
    if (!qualityReport) {
      message.warning('请先完成分析');
      return;
    }

    message.loading({ content: '正在生成报告...', key: 'export', duration: 0 });

    try {
      const blob = await exportReport();

      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `优化报告_${new Date().getTime()}.pdf`;
      a.click();
      URL.revokeObjectURL(url);

      message.success({ content: '报告已导出', key: 'export' });
    } catch (error) {
      message.error({ content: '导出失败', key: 'export' });
    }
  };

  /**
   * 应用优化版本
   */
  const handleApplyVersion = () => {
    if (!selectedVersionId) {
      message.warning('请先选择一个版本');
      return;
    }

    const selectedVersion = optimizedVersions.find(v => v.id === selectedVersionId);
    if (!selectedVersion) return;

    // 应用到编辑器
    useEditorStore.getState().setContent(selectedVersion.content);

    message.success('优化版本已应用到编辑器');
    setShowVersionModal(false);
  };

  return (
    <div className="optimization-panel">
      {/* 操作按钮栏 */}
      <Card className="action-bar" bordered={false}>
        <Space size="middle" wrap>
          <Button
            type="primary"
            size="large"
            icon={<ThunderboltOutlined />}
            loading={isAnalyzing}
            onClick={handleAnalyze}
          >
            开始分析
          </Button>

          <Button
            icon={<SearchOutlined />}
            disabled={!qualityReport}
            onClick={() => handleQuickOptimize('seo')}
            loading={isOptimizing}
          >
            SEO优化
          </Button>

          <Button
            icon={<ReadOutlined />}
            disabled={!qualityReport}
            onClick={() => handleQuickOptimize('readability')}
            loading={isOptimizing}
          >
            可读性优化
          </Button>

          <Button
            icon={<FileTextOutlined />}
            disabled={!qualityReport}
            onClick={() => handleQuickOptimize('professional')}
            loading={isOptimizing}
          >
            专业深度优化
          </Button>

          <Button
            icon={<CompareOutlined />}
            disabled={!qualityReport}
            onClick={handleGenerateVersions}
            loading={isOptimizing}
          >
            生成多版本
          </Button>

          <Button
            icon={<DownloadOutlined />}
            disabled={!qualityReport}
            onClick={handleExportReport}
          >
            导出报告
          </Button>
        </Space>
      </Card>

      {/* 分析结果展示 */}
      {isAnalyzing ? (
        <Card style={{ marginTop: 16 }}>
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
            <p style={{ marginTop: 16, color: '#8c8c8c' }}>正在分析文章质量...</p>
          </div>
        </Card>
      ) : qualityReport ? (
        <Card style={{ marginTop: 16 }} bordered={false}>
          <Tabs activeKey={activeTab} onChange={setActiveTab}>
            <TabPane
              tab={
                <Space>
                  <FileTextOutlined />
                  <span>质量分析</span>
                </Space>
              }
              key="quality"
            >
              <QualityReport
                report={qualityReport}
                onApplySuggestion={handleApplySuggestion}
              />
            </TabPane>

            <TabPane
              tab={
                <Space>
                  <SearchOutlined />
                  <span>SEO分析</span>
                </Space>
              }
              key="seo"
            >
              {seoAnalysis ? (
                <SEOPanel analysis={seoAnalysis} />
              ) : (
                <div className="empty-state">
                  <p>暂无SEO分析数据</p>
                </div>
              )}
            </TabPane>

            <TabPane
              tab={
                <Space>
                  <ReadOutlined />
                  <span>可读性分析</span>
                </Space>
              }
              key="readability"
            >
              {readabilityAnalysis ? (
                <ReadabilityPanel analysis={readabilityAnalysis} />
              ) : (
                <div className="empty-state">
                  <p>暂无可读性分析数据</p>
                </div>
              )}
            </TabPane>

            {optimizedVersions.length > 0 && (
              <TabPane
                tab={
                  <Space>
                    <CompareOutlined />
                    <span>版本对比</span>
                  </Space>
                }
                key="compare"
              >
                <VersionCompare
                  originalContent={content}
                  versions={optimizedVersions}
                  selectedVersionId={selectedVersionId}
                  comparisonData={comparisonData}
                  onSelectVersion={selectVersion}
                  onCompare={(versionId) => {
                    const version = optimizedVersions.find(v => v.id === versionId);
                    if (version) {
                      compareVersions(content, version.content);
                    }
                  }}
                />
              </TabPane>
            )}
          </Tabs>
        </Card>
      ) : (
        <Card style={{ marginTop: 16 }}>
          <div className="empty-state">
            <FileTextOutlined style={{ fontSize: 64, color: '#d9d9d9' }} />
            <h3>开始分析你的文章</h3>
            <p>点击"开始分析"按钮，获取全面的质量评估和优化建议</p>
          </div>
        </Card>
      )}

      {/* 版本选择模态框 */}
      <Modal
        title="选择优化版本"
        open={showVersionModal}
        onCancel={() => setShowVersionModal(false)}
        onOk={handleApplyVersion}
        okText="应用版本"
        cancelText="取消"
        width={900}
      >
        {optimizedVersions.length > 0 && (
          <VersionCompare
            originalContent={content}
            versions={optimizedVersions}
            selectedVersionId={selectedVersionId}
            comparisonData={comparisonData}
            onSelectVersion={selectVersion}
            onCompare={(versionId) => {
              const version = optimizedVersions.find(v => v.id === versionId);
              if (version) {
                compareVersions(content, version.content);
              }
            }}
          />
        )}
      </Modal>
    </div>
  );
};
